package com.gmadmin.sysadmin.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gmadmin.commoncore.exception.BaseException;
import com.gmadmin.gmmbg.entity.SysRole;
import com.gmadmin.gmmbg.entity.SysUser;
import com.gmadmin.gmmbg.mapper.SysRoleMapper;
import com.gmadmin.gmmbg.service.ISysUserService;
import com.gmadmin.sysadmin.security.dto.AuthorityDto;
import com.gmadmin.sysadmin.security.dto.UserDetailsDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final ISysUserService userService;
    private final SysRoleMapper sysRoleMapper;
    private final OnlinePermsService onlinePermsService;

    @Override
    public UserDetailsDto loadUserByUsername(String username) {
        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq("username", username).eq("del_flag", 0));
        if (user == null) {
            throw new BaseException("用户不存在");
        } else {
            if(user.getStatus() != null && user.getStatus() == 1){
                List<SysRole> roles = sysRoleMapper.findByUserId(user.getId());
                Set<String> roleCodes = roles.stream().filter(Objects::nonNull).map(SysRole::getRoleCode).collect(Collectors.toSet());
                // 获取用户的权限
                List<AuthorityDto> authorities = onlinePermsService.findPermsDto(roleCodes);
                // 初始化UserDetailsDto
                return new UserDetailsDto(user, authorities, roleCodes);
            } else {
                throw new BaseException("账号未激活！");
            }
        }
    }

}
